<!--
  Copyright (c) 2018-2999 广州市蓝海创新科技有限公司 All rights reserved.

  https://www.mall4j.com/

  未经允许，不可做商业用途！

  版权所有，侵权必究！
-->

<template>
  <view class="Mall4j page-modify-logistics">
    <view class="logistics">
      <view
        v-for="(item,i) in dateForm"
        :key="i"
        class="good-logistics"
      >
        <view class="good-info">
          <view class="package">
            包裹{{ i + 1 }}
          </view>
          <view class="good-num">
            （共{{ item.totalCount }}件商品）
          </view>
        </view>
        <view class="logistics-info">
          <view class="list">
            <view class="left">
              <text class="info">
                发货方式
              </text>
              <text class="content">
                {{ shippingMethods[shippingIndex[i]] ? shippingMethods[shippingIndex[i]].name : '' }}
              </text>
            </view>
            <!-- <text class="iconfont">&#xe775;</text> -->
          </view>
          <view
            v-if="[0,1].includes(item.deliveryType)"
            class="list"
          >
            <view class="left">
              <text class="info">
                配送方式
              </text>
              <text class="content">
                {{ ["线上发货",'线下发货'][item.deliveryType] }}
              </text>
            </view>
            <!-- <text class="iconfont">&#xe775;</text> -->
          </view>
          <view
            v-if="[0,1].includes(item.deliveryType)"
            class="list"
            @tap="item.deliveryType===1?toSelecteDelivery(i):void(0)"
          >
            <view class="left">
              <text class="info">
                快递公司
              </text>
              <text
                v-if="item.deliveryType===1"
                class="content"
                :style="{color:selectedDeliveryArr[i].dvyName ? '' : '#999999'}"
              >
                {{ selectedDeliveryArr[i].dvyName || '请选择物流公司' }}
              </text>
              <text
                v-else
                class="content"
              >
                {{ deliveryCompanyType[item.dvyId-1].label }}
              </text>
            </view>
            <!-- <text class="iconfont">&#xe775;</text> -->
            <view
              v-if="item.deliveryType===1"
              class="icon"
            />
          </view>
          <view
            v-if="[0,1].includes(item.deliveryType)"
            class="list"
          >
            <view class="left">
              <text class="info">
                快递单号
              </text>
              <input
                v-model="item.dvyFlowId"
                class="input"
                type="text"
                :disabled="item.deliveryType === 0"
                placeholder="请输入快递单号"
                placeholder-class="placeholder-class"
              >
            </view>
            <!-- <text class="iconfont" @tap="deliveryModeOpen">&#xe775;</text> -->
          </view>
        </view>
      </view>
    </view>
    <button
      type="primary"
      class="btn"
      @tap="submit"
    >
      确认修改
    </button>
    <!-- 选择配送方式 -->
    <select-popup
      v-if="showSelecMode"
      :value="dateForm[index].deliveryType"
      :data="shippingMethods"
      @submit-data="getDeliveryMethod"
      @cancal="cancal"
    />
  </view>
</template>

<script setup>
import { reactive } from 'vue'

const Data = reactive({
  orderNumber: '',
  selectedDelivery: {},
  selectedDeliveryArr: [],
  showSelecMode: false,
  shippingMethods: [
    {
      name: '快递配送',
      value: 0
    },
    {
      name: '快递配送',
      value: 1
    },
    {
      name: '无需快递',
      value: 3
    }
  ],
  dateForm: [],
  index: 0,
  shippingIndex: [],
  isFirst: true
})
const deliveryCompanyType = [{
  value: 1,
  label: '顺丰速运'
}, {
  value: 2,
  label: '京东快递'
}, {
  value: 3,
  label: '圆通速递'
}, {
  value: 4,
  label: '韵达快递'
}, {
  value: 5,
  label: '中通快递'
}, {
  value: 6,
  label: '申通快递'
}, {
  value: 7,
  label: '百世快递'
}, {
  value: 8,
  label: 'EMS'
}]

const { selectedDeliveryArr, showSelecMode, shippingMethods, dateForm, index, shippingIndex } = toRefs(Data)

const { proxy } = getCurrentInstance()

watch(() => Data.selectedDelivery, (val) => {
  Data.selectedDeliveryArr[Data.index] = val
  Data.dateForm[Data.index].dvyId = val.dvyId
  proxy.$forceUpdate()
}, { deep: true })

onLoad((options) => {
  Data.orderNumber = options.orderNumber
  getOrderDeliveriesById()
})

onShow(() => {
  if (uni.getStorageSync('bbcSelectedDelivery') && Data.isFirst === false) {
    Data.selectedDelivery = uni.getStorageSync('bbcSelectedDelivery')
    uni.removeStorageSync('bbcSelectedDelivery')
  }
  Data.isFirst = false
})

// 订单包裹物流详情
const getOrderDeliveriesById = () => {
  http.request({
    url: `/order/delivery/getOrderDeliveries/${Data.orderNumber}`,
    method: 'PUT'
  }).then(({ data: res }) => {
    if (res) {
      Data.dateForm = res
      res.forEach(item => {
        const index = Data.shippingMethods.findIndex(el => {
          return el.value === item.deliveryType
        })
        Data.shippingIndex.push(index)
        Data.selectedDeliveryArr.push({ dvyId: item.dvyId })
        let count = 0
        item.orderItems.forEach(el => {
          count += el.prodCount
        })
        item.totalCount = count
      })
      getDeliveryList()
    }
  })
}

/**
     * 获取物流公司列表
     */
const getDeliveryList = () => {
  http.request({
    url: '/admin/delivery/list',
    method: 'GET'
  }).then(({ data }) => {
    data.forEach((item) => {
      Data.selectedDeliveryArr.forEach(el => {
        if (item.dvyId === el.dvyId) {
          el.dvyName = item.dvyName
        }
      })
    })
  })
}

const getDeliveryMethod = (value) => {
  Data.dateForm[Data.index].deliveryType = value
  Data.shippingIndex[Data.index] = Data.shippingMethods.findIndex(item => {
    return item.value === value
  })
  Data.showSelecMode = false
}

const cancal = () => {
  Data.showSelecMode = false
}

// 选择物流公司
const toSelecteDelivery = (index) => {
  Data.index = index
  uni.navigateTo({
    url: `/package-order/pages/select-logistics/select-logistics?dvyId=${Data.selectedDeliveryArr[Data.index].dvyId}`
  })
}

// 修改订单包裹物流
const submit = () => {
  const reg = /^[a-zA-Z0-9]{4,30}$/
  const flag = Data.dateForm.some(item => {
    if (item.deliveryType === 1) {
      item.dvyFlowId = item.dvyFlowId.trim()
      if (item.dvyFlowId.length === 0) {
        uni.showToast({
          title: '快递单号不能为空！',
          icon: 'none'
        })
        return true
      } else if (!reg.test(item.dvyFlowId)) {
        uni.showToast({
          title: '请输入正确的快递单号！',
          icon: 'none'
        })
        return true
      }
    }
    return false
  })

  if (flag) return
  uni.showLoading({
    mask: true
  })
  http.request({
    url: '/order/delivery/updateOrderDeliveries',
    method: 'PUT',
    data: {
      deliveryOrders: Data.dateForm
    }
  }).then(() => {
    uni.hideLoading()
    uni.showToast({
      title: '操作成功！',
      icon: 'none',
      success: () => {
        setTimeout(() => {
          uni.navigateBack({
            delta: 1
          })
        }, 1500)
      }
    })
  })
}
</script>

<style lang="scss" scoped>
@use "modify-logistics";
</style>
